package com.shire.shire_interface.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.zip.GZIPInputStream;

public class RequestHelper {
    private static final String GZIPCODING = "gzip";

    public static String getBodyString(HttpServletRequest request, String encoding) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        GZIPInputStream gzipInputStream = null;
        try {
            inputStream = request.getInputStream();
            if(GZIPCODING.equalsIgnoreCase(encoding)){
                gzipInputStream = new GZIPInputStream(inputStream);
                reader = new BufferedReader(
                        new InputStreamReader(gzipInputStream, Charset.forName("UTF-8")));
            }
            else {
                reader = new BufferedReader(
                        new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            }

            char[] bodyCharBuffer = new char[1024];
            int len = 0;
            while ((len = reader.read(bodyCharBuffer)) != -1) {
                sb.append(new String(bodyCharBuffer, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(gzipInputStream!=null){
                try{
                    gzipInputStream.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}
